package com.hardy.tree;

import java.util.Arrays;

/**
 * Author: fuxh3@lenovo.com
 * Date: Created in 2017/12/7 0007
 */
public class Trie {
    private TrieNode node;

    public Trie(){
        this.node = new TrieNode(' ');
    }

    public void insert(String words){
        if(search(words)==true){
            return;
        }
        TrieNode current = node;
        for(int i=0;i<words.length();i++){
            TrieNode child = current.subNode(words.charAt(i));
            if(child != null){
                current = child;
            }else{
                current.childList.add(new TrieNode(words.charAt(i)));
                current = current.subNode(words.charAt(i));
            }
            current.count++;
        }
        current.isEnd=true;
    }

    public boolean search(String words){
        TrieNode current = node;
        for (int i=0;i<words.length();i++){
            if(current.subNode(words.charAt(i))==null){
                return false;
            }else{
                current = current.subNode(words.charAt(i));
            }
        }
        if(current.isEnd=true){
            return true;
        }
        return false;
    }

    public void deleteWord(String words){
        if(search(words)==false){
            return;
        }
        TrieNode current = node;
        for(int i=0;i<words.length();i++){
            TrieNode child = current.subNode(words.charAt(i));
            if(child.count==1){
                current.childList.remove(child);
                return;
            }else {
                child.count--;
                current = child;
            }
        }
        current.isEnd=false;
    }

    public static void main(String[] args) {
        Trie trie = new Trie();
        trie.insert("ball");
        trie.insert("balls");
        trie.insert("sense");
        trie.insert("s");
        // testing deletion
        System.out.println(trie.search("l"));
        System.out.println(trie.search("balls"));
        System.out.println(trie.search("ba"));
        System.out.println(trie.search("s"));
        System.out.println(trie.search("sense"));
        //trie.deleteWord("balls");
        System.out.println(trie.search("balls"));
        System.out.println(trie.search("ball"));
    }
}
